function[trainingSet, testSet] = splitIntoTrainingAndTest(featureVecs, percent_training) %splitDefFilePath)
% Splits the given set of feature vectors into training and test set
% according to the definition in a file.
%
%   INPUT
%   featureVecs.........A set of feature vectors as returned by loadWines()
%                       for example.
%   splitDefFilePath....The path to a file containing a comma-separated
%                       list of feature vector indizes that shall be used
%                       as training set. The remaining feature vectors of
%                       the given set will becoe the test set.
%   OUTPUT
%   trainingSet.........The vectors of featureVecs specified in the file.
%   testSet.............The remaining vectors of featureVecs.

   % OLD file based selection
   % file = fopen(splitDefFilePath);
   % indizes = fscanf(file, '%u,');
   % fclose(file);
   % trainingSet = featureVecs(:, indizes);
   % testSet = featureVecs;
   % testSet(:, indizes) = [];
   
   %percent_training = 0.5;
   
   %NEW randomized method
   %disp(featureVecs);;
   %number of elements
   
   %disp(featureVecs);
   featureVecs = sortrows(featureVecs',1)';
   %disp(featureVecs);
   
   count = size(featureVecs,2);
   
   %number of classes
   classes = max(featureVecs(1,:));
  
   %count elements per class
   class_counts = zeros(classes,1);
   
   for i=1:count
      class_counts(featureVecs(1,i)) = class_counts(featureVecs(1,i))+1;
   end
   %disp(class_counts);
   
   %count number of elements per classes that should be used for training
   class_counts_train = zeros(classes,1);
   for i=1:classes
      class_counts_train(i) = floor(class_counts(i)*percent_training);
   end
   %disp(class_counts_train);
  
   %disp(count);
   
   %give every item a random value
   randomvalues = zeros(count,2);
   for i = 1:count
       randomvalues(i,1) = i;
       randomvalues(i,2) = rand();
   end
   
   indices_training = zeros(0);

   %loop over classes
   sum=1;
   for i=1:classes
       
      %subset of rnd values per class
      rndforclass = randomvalues(sum:(sum+class_counts(i)-1),:);
      sum = sum + class_counts(i); %required for subset access
      
      %sort (index,rnd) vector after rnd value
      sorted = sortrows(rndforclass,2);
      
      %take first x elements from sorted vectors and use as training set
      %for this class
      indices = sorted(1:class_counts_train(i),1);
      %disp(indices);
      
      %concatenate the indices for this class with all other class indices
      indices_training = cat(1,indices_training,indices);
      %disp(indices_training);
   end
   
   %disp(indices_training);
   
   %disp(randomvalues);
   
   trainingSet = featureVecs(:, indices_training);
   testSet = featureVecs;
   testSet(:, indices_training) = [];
   
   
   %disp(trainingSet);
   %disp(testSet);
end
